package com.learning.spring.cloud.domain.service.impl;

import com.learning.spring.cloud.domain.model.Product;
import com.learning.spring.cloud.domain.repo.ProductRepo;
import com.learning.spring.cloud.domain.service.ProductService;
import com.learning.spring.cloud.dto.ProductDto;
import com.learning.spring.cloud.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductRepo productRepo;

    @Override
    public ProductDto save(ProductDto productDto) {
        Product product = ProductMapper.INSTANCE.toEntity(productDto);
        Product updated = productRepo.save(product);
        return ProductMapper.INSTANCE.toDto(updated);
    }

    @Override
    public ProductDto findByCode(String code) {
        Product product = productRepo.findByCode(code);
        return ProductMapper.INSTANCE.toDto(product);
    }

    @Override
    public List<ProductDto> findAll() {
        Iterable<Product> productIterable = productRepo.findAll();

        List<ProductDto> result = new ArrayList<>();
        productIterable.forEach(p -> result.add(ProductMapper.INSTANCE.toDto(p)));
        return result;
    }
}
